package com.leyou.controller;

import com.leyou.Parameter;
import com.leyou.ResponseData;
import com.leyou.entity.Category;
import com.leyou.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/list")
    public ResponseData getCategoryByParentId(Long pid, Parameter parameter) {
        try {
            if (pid == null || pid.longValue() < 0) {
                log.error("parentId请求参数异常!");
                return ResponseData.error(400, "parentId不能为空!", parameter);
            }
            // 异常测试代码
//            int a = 1/0;
            List<Category> categories = categoryService.getCategoryByParentId(pid);
            log.info(categories.toString());
            ResponseData<List<Category>> rd = new ResponseData<>();
            rd.setParameter(parameter);
            rd.setData(categories);
            return rd;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
        return ResponseData.error(5000, "服务器繁忙!", parameter);
    }

    // 根据多个分类id查询分类名称
    @GetMapping("/{ids}")
    public ResponseData queryNameByIds(@RequestParam(name = "ids") List<Long> ids) {
        try {
            List<String> names = categoryService.getCategoryNameByIds(ids);
            return ResponseData.ok(names);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.error();
    }
}
